package com.mobzilla.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.os.AsyncTask;
import android.util.Log;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.mobzilla.util.Constants;
import com.mobzilla.util.Lock;

public class LoginServiceImpl implements LoginService
{

	@Override
	public boolean authenticateUser(String userName, String password)
	{
		String url = Constants.BASE_URL + "/bug?username=" + userName.toLowerCase() + "&password=" + password;

		Lock<String> lock = new Lock<String>();
		HTTPRequestAsync async = new HTTPRequestAsync(url, lock);
		AsyncTask<String, Void, String> response = null;
		response = async.execute();

		while(!lock.isDataSet())
		{
			
		}

		if (lock.getData() == null)
		{
			return false;
		}
		
		JsonParser parser = new JsonParser();
		JsonElement element = parser.parse(lock.getData());
		JsonObject map = element.getAsJsonObject();
		
		String msgValue = "";
		
		if ((map.get(Constants.MESSAGE) != null) && (msgValue = map.get(Constants.MESSAGE).getAsString()) != null)
		{
			if (msgValue.contains("Invalid username or password"))
			{
				return false;
			}
			else if ((map.get(Constants.CODE) != null) && map.get(Constants.CODE).getAsInt() == 300)
			{
				return false;
			}
		}
		return true;

	}

}
